package com.zx.zxpicture.domain.picture.template;

import cn.hutool.core.io.FileUtil;
import com.zx.zxpicture.infrstructure.common.ErrorCode;
import com.zx.zxpicture.infrstructure.exception.BusinessException;
import com.zx.zxpicture.infrstructure.exception.ThrowUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

@Slf4j
@Service
public class FileUpload extends PictureUploadTemplate{


    @Override
    public <T> void validPicture(T inputSource) {
        MultipartFile multipartFile = (MultipartFile) inputSource;
        ThrowUtils.throwIf(multipartFile == null, ErrorCode.PARAMS_ERROR, "文件不能为空");
        // 1. 校验文件大小
        //文件大小单位是字节
        long fileSize = multipartFile.getSize();
        //1m转为字节
        final long ONE_M = 1024*1024;
        ThrowUtils.throwIf(fileSize > 2 * ONE_M, ErrorCode.PARAMS_ERROR, "文件大小不能超过 2M");
        // 2. 校验文件后缀
        String fileSuffix = FileUtil.getSuffix(multipartFile.getOriginalFilename());
        // 允许上传的文件后缀
        final List<String> ALLOW_FORMAT_LIST = Arrays.asList("jpeg", "jpg", "png", "webp");
        ThrowUtils.throwIf(!ALLOW_FORMAT_LIST.contains(fileSuffix), ErrorCode.PARAMS_ERROR, "文件类型错误");
    }

    /**
     * 重写获取文件名
     * @param inputSource
     * @return
     * @param <T>
     */
    @Override
    public <T> String getFileName(T inputSource) {
        MultipartFile multipartFile = (MultipartFile) inputSource;
        //获取文件名
        return multipartFile.getOriginalFilename();
    }

    /**
     * 图片写入文件
     * @param inputSource 输入方式
     * @param file 要写入图片的文件
     * @param <T>
     */
    @Override
    public <T> void getFile(T inputSource, File file) {
        MultipartFile multipartFile = (MultipartFile) inputSource;
        try {
            multipartFile.transferTo(file);
        } catch (IOException e) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "文件写入失败");
        }
    }
}
